import path from 'path'
import fs from 'fs'
import app from '@/app'
import pdf from '@/app/pdf'
import storage from '@/app/storage'
import server from '@/api/server'
import base from '@/app/model'

import accountModel from '@/model/account'
import templateModel from '@/plugin/config/model/template'

// 继承总模型
const model = new base;

model.get = () => {
  let printer = storage.get('printer')
  if(!printer) {
    printer = {}
  }

  model.setData(printer)
}

model.update = (data) => {
  storage.set('printer', data)
  model.get()
}

// 获取小票打印机
model.getSmall = () => {
  const printer = model.getData().small
  if(!printer) {
    app.ui.message('warning', 'print_small')
    return false
  }

  return printer
}

// 获取A4打印机
model.getA4 = () => {
  const printer = model.getData().a4
  if(!printer) {
    app.ui.message('warning', 'print_a4')
    return false
  }

  return printer
}

// 获取缓存路径
model.getPath = () => {
  const path = model.getData().path
  if(!path) {
    app.ui.message('warning', 'print_path')
    return false
  }

  return path
}

// 开钱箱
model.cashbox = async() => {
  const printer = model.getSmall()
  if(!printer) return

  await server.printCashBox(printer)
  return true
}

// 使用模版
model.getTemplate = (name, data) => {
  // 从配置中获取
  const template = templateModel.printTemplate(name)

  if(!template) {
    app.ui.message('warning', 'template')
    return false
  }

  return { 
    version: template.version, 
    view: model.buildTemplate(template.view, data, template.data)
  }
}

// 生成模版
model.buildTemplate = (view, data, template) => {
  const account = accountModel.getData()
  const user = accountModel.getUser()
  const _app = app

  return eval('(() => {' + view + '})()', _app, data, template, account, user) 
}

// 小票打印
model.printSmall = (view) => {
  // 获取打印机
  const printer = model.getSmall()
  if(!printer) return

  server.printTemplate(printer, view)
}

// PDF打印
model.printPDF = async (name, view) => {
  // 获取打印机
  const printer = model.getA4()
  if(!printer) return

  // 获取缓存目录
  const dir = model.getPath()
  if(!dir) return

  // 检查文件存在
  const file = path.join(dir, name + '.pdf')

  // 不存在就生成PDF
  if(!fs.existsSync(file)) {
    const doc = pdf.load(view)
    await doc.write(file)
  }

  // 判断是否预览
  if(printer == 'show') {
    return app.window.pdfShow(file)
  }

  // 打印PDF
  server.printPdf(printer, file)
}

// 打印模版
model.printTemplate = (name, data, file) => {
  // 获取模版
  const { version, view } = model.getTemplate(name, data)

  if(version == 'js') {
    model.printSmall(view)
  } else {
    model.printPDF(file, view)
  }
}


// 获取一次
model.get()

export default model